<template>
  <h2>热处理图像数据详情: </h2>
  <a-divider
      type="horizontal"
      :style="{ borderColor: '#19a7ff', borderWidth: '2px' }"
  />

  <div class="scroll-container">
    <a-spin :spinning="loading">
      <a-row :gutter="20">
        <a-col
            v-for="(image, index) in Data"
            :key="index"
            :span="6"
        >
          <div class="image-container">
            <a-image
                class="image-style"
                :src="image.imgUrl"
                :hash="image.hash"
                :alt="image.name"
                :preview="false"
                @click="handleClickPic(image)"
                @error="handleImageError(image)"
            />
            <div v-if="image.loadError" class="error-overlay">
              图片加载失败
            </div>
          </div>
        </a-col>
      </a-row>
      <a-empty v-if="!loading && Data.length === 0" description="暂无图片数据" />
    </a-spin>
  </div>
</template>

<script>
import axiosInstance from "@/axios/axios.js";
import { message } from 'ant-design-vue';

export default {
  name: "HeatTreatmentImages",
  data() {
    return{
      loading: false,
      Data: [],
    }
  },

  async created(){
    // 检查登录状态
    if (!this.$cookies.get('jwt') || !sessionStorage.getItem("isLogin")) {
      message.warning('请先登录');
      this.$router.push('/login');
      return;
    }

    // 检查必要参数
    const requiredParams = ['batch_id', 'experiment_set_name', 'experiment_batch_name'];
    const missingParams = requiredParams.filter(param => !this.$route.query[param]);
    if (missingParams.length > 0) {
      message.error('缺少必要的参数');
      this.$router.push('/myData');
      return;
    }

    await this.initImageFile();
  },

  methods:{
    async initImageFile(){
      this.loading = true;
      try {
        const response = await axiosInstance({
          method: "POST",
          url: "/myData/getHeatTreatmentImages",
          headers: {
            Authorization: `Bearer ${this.$cookies.get("jwt")}`
          },
          data: {
            username: this.$cookies.get("username"),
            dataId: this.$route.query.batch_id,
            experimentSetName: this.$route.query.experiment_set_name,
            batchName: this.$route.query.experiment_batch_name,
          },
        });

        // 打印完整的响应数据
        console.log('Backend Response:', response.data);

        if (response.data?.data?.images && response.data.data.url) {
          const imagesPath = response.data.data.url;
          
          // 打印原始图片数据
          console.log('Original Images Data:', response.data.data.images);

          this.Data = response.data.data.images.map(item => {
            // 打印每个图片对象的详细信息
            console.log('Processing Image Item:', {
              name: item.name,
              tx_hash: item.tx_hash,  // 特别关注 tx_hash 字段
              experiment_set_id: item.experiment_set_id,
              batch_id: item.batch_id,
              experiment_id: item.experiment_id,
              raw_item: item  // 打印完整的原始对象
            });

            return {
              ...item,
              imgUrl: encodeURI(imagesPath + item.name),
              loadError: false
            };
          });

          // 打印处理后的数据
          console.log('Processed Data:', this.Data);
          
          // 预加载图片
          this.Data.forEach(image => {
            const img = new Image();
            img.onerror = () => {
              const index = this.Data.findIndex(i => i.imgUrl === image.imgUrl);
              if (index !== -1) {
                this.Data[index].loadError = true;
              }
            };
            img.src = image.imgUrl;
          });
          
          await this.loadTiffImages();
        } else {
          console.warn("No images data in response:", response.data);
          this.Data = [];
        }
      } catch (error) {
        console.error('获取图片数据失败:', error);
        if (error.response) {
          console.error('Error Response:', error.response.data);
        }
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(`获取数据失败: ${error.response?.data?.message || error.message}`);
        }
      } finally {
        this.loading = false;
      }
    },

    async loadTiffImages() {
      for (const image of this.Data) {
        if (image.imgUrl.endsWith('.tif')) {
          try {
            const response = await fetch(image.imgUrl);
            if (!response.ok) {
              throw new Error('Failed to load TIF image');
            }
            const buffer = await response.arrayBuffer();
            const tiff = new Tiff({ buffer });
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const width = tiff.width();
            const height = tiff.height();
            canvas.width = width;
            canvas.height = height;
            const imageData = tiff.toCanvas();
            ctx.drawImage(imageData, 0, 0, width, height);
            image.imgUrl = canvas.toDataURL();
          } catch (error) {
            console.error('Error loading TIF image:', error);
            image.loadError = true;
          }
        }
      }
    },

    handleClickPic(image) {
      // 打印点击的图片对象信息
      console.log('Clicked Image Data:', {
        image_data: image,
        tx_hash: image.tx_hash,
        experiment_set_id: image.experiment_set_id,
        batch_id: image.batch_id,
        experiment_id: image.experiment_id
      });

      if (image.loadError) {
        message.error('图片加载失败，无法查看详情');
        return;
      }

      if (!image.experiment_set_id || !image.batch_id || !image.tx_hash) {
        console.warn('Missing required fields:', {
          experiment_set_id: image.experiment_set_id,
          batch_id: image.batch_id,
          tx_hash: image.tx_hash
        });
        message.error('图片信息不完整');
        return;
      }

      // 显示加载提示
      const loadingKey = 'loadingImage';
      message.loading({ content: '正在处理图片...', key: loadingKey });

      // 先将图片转换为base64
      fetch(image.imgUrl)
        .then(response => {
          if (!response.ok) {
            throw new Error('图片获取失败');
          }
          return response.blob();
        })
        .then(blob => {
          return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onloadend = () => resolve(reader.result);
            reader.onerror = reject;
            reader.readAsDataURL(blob);
          });
        })
        .then(base64Data => {
          // 关闭加载提示
          message.success({ content: '处理完成', key: loadingKey });
          
          // 构建查询参数
          const query = {
            imgUrl: base64Data,
            imgUrlFortif: base64Data,
            experimentSetId: image.experiment_set_id,
            batchId: image.batch_id,
            tx_hash: image.tx_hash,  // 使用 tx_hash 而不是 hash
            metadata: JSON.stringify({
              width: image.width,
              height: image.height,
              file_size: image.file_size,
              mime_type: image.mime_type,
              created_at: image.created_at,
              file_hash: image.file_hash,
              tx_hash: image.tx_hash,  // 添加 tx_hash 到元数据
              metadata: {
                fileName: image.name
              }
            })
          };

          if (image.experiment_id && image.experiment_id !== '-1') {
            query.experimentId = image.experiment_id;
          }

          this.$router.push({
            path: '/detail',
            query
          });
        })
        .catch(error => {
          console.error('图片处理失败:', error);
          message.error({ content: '图片处理失败，请稍后重试', key: loadingKey });
        });
    },

    handleImageError(image) {
      const index = this.Data.findIndex(item => item.image_id === image.image_id);
      if (index !== -1) {
        this.Data[index].loadError = true;
      }
    },
  }
}
</script>

<style scoped>
.scroll-container {
  max-width: 90vw;
  margin: auto;
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.image-container {
  position: relative;
  max-width: 90%;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
  cursor: pointer;
}

.image-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.image-style {
  max-width: 100%;
  max-height: 200px;
  display: block;
  margin: auto;
  object-fit: contain;
}

.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.1);
  color: #ff4d4f;
  font-size: 14px;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .image-container .a-image {
    max-height: 150px;
  }
}

@media (max-width: 480px) {
  .image-container .a-image {
    max-height: 100px;
  }
}
</style>